<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in person" :key="item.id">
          <td>{{index + 1}}</td>
          <td>{{item.uname}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
    data(){
      return {
        person:JSON.parse(localStorage.getItem('person')) || [],
         uname:'',
          age:'',
          gender:'',
          id:''
      }
    },
    methods: {
      add(){
        if(this.uname && this.age > 0 && this.gender){
          // 先判断是否携带id，有就只做修改
         if(this.id){
          // 删除之后id和索引会对不上，所以要findIndex
          this.person.splice(this.person.findIndex(item=>this.id === item.id), 1, {
            id:this.id,
            uname:this.uname,
            age:this.age,
            gender:this.gender})
            // 清空id 以便下次编辑时重新赋值
            this.id = ''
         } else{
           this.person.push({
            id:this.person.length ? this.person.at(-1).id + 1 : 1,
            uname:this.uname,
            age:this.age,
            gender:this.gender
          })
         }
          this.uname = '',
          this.age = '',
          this.gender = ''
        } else{
          alert('输入内容不得为空！')
        }
      },
      del(id){
       this.person = this.person.filter(item=> item.id !== id)
      },
      edit(i){
        this.uname = this.person.at(i).uname
        this.age = this.person.at(i).age
        this.gender = this.person.at(i).gender
        // 多加一项id 方便定位
        this.id = this.person.at(i).id
    },
},
watch:{
      person(){
        localStorage.setItem('person',JSON.stringify(this.person))
      }
    }
}
</script>
